<template>
  <div style="padding: 20px">
    <!-- 收费标准审批 -->
    <a-card :bordered="false" style="height: 800px">
      <a-form layout="inline" :model="formState" ref="formRef">
        <div style="display: flex">
          <a-form-item label="申请时间" name="apply">
            <a-range-picker
              allowClear
              v-model:value="formState.apply"
              value-format="YYYY-MM-DD"
            />
          </a-form-item>
          <a-form-item label="审批时间" name="approval">
            <a-range-picker
              allowClear
              v-model:value="formState.approval"
              value-format="YYYY-MM-DD"
            />
          </a-form-item>
          <a-form-item label="审批人" name="approver">
            <a-tree-select
              v-model:value="formState.approver"
              show-search
              style="width: 320px"
              :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
              placeholder="请选择审批人"
              allow-clear
              tree-default-expand-all
              :tree-data="treeDataId"
              tree-node-filter-prop="label"
              @change="onChange"
            >
              <template #title="{ value: val, label }">
                <b v-if="val === 'parent 1-1'" style="color: #08c">sss</b>
                <template v-else>{{ label }}</template>
              </template>
            </a-tree-select>
          </a-form-item>
          <a-form-item label="审批状态" name="approvalStatus">
            <a-select
              allowClear
              v-model:value="formState.approvalStatus"
              placeholder="请选择"
              style="width: 200px"
              autocomplete="off"
            >
              <a-select-option value="审核中">审核中</a-select-option>
              <a-select-option value="同意">同意</a-select-option>
              <a-select-option value="拒绝">拒绝</a-select-option>
            </a-select>
          </a-form-item>
        </div>

        <div style="display: flex; margin-top: 20px">
          <a-form-item label="标准名称" name="jfbzName">
            <a-input
              v-model:value="formState.jfbzName"
              placeholder="请输入标准名称"
              autocomplete="off"
              allowClear
            />
          </a-form-item>
          <a-form-item>
            <a-button type="primary" @click.prevent="onSubmit">查询</a-button>
            <a-button style="margin-left: 10px" @click="resetForm"
              >重置</a-button
            >
          </a-form-item>
        </div>
      </a-form>
      <a-table
        :columns="columns"
        :data-source="dataSource"
        bordered
        size="middle"
        :row-class-name="
          (_record: any, index: number) =>
            index % 2 === 1 ? 'table-striped' : null
        "
        :pagination="pagination"
        @change="handleTableChange"
        :scroll="{ x: 3000, y: 550 }"
        style="margin-top: 20px"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'active'">
            <a-button
              :disabled="record.approvalStatus != '审核中'"
              type="link"
              @click="onEdit(record, '0')"
            >
              同意
            </a-button>
            <a-button
              :disabled="record.approvalStatus != '审核中'"
              type="link"
              danger
              @click="onEdit(record, '1')"
            >
              拒绝
            </a-button>
          </template>
          <template v-if="column.dataIndex === 'discountType'">
            <a-button
              type="link"
              @click="discountClick(record)"
              v-if="record.discountType == '分时段优惠'"
              >分时段优惠</a-button
            >
            <span v-else>{{ record.discountType }}</span>
          </template>

          <template v-if="column.dataIndex === 'download'">
            <a-button type="link" @click="downloadClick(record)">下载</a-button>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 同意 -->
    <a-modal
      v-model:open="isConsentOpen"
      width="1000px"
      title="操作审批"
      @ok="ConsentOk"
    >
      <a-textarea
        v-model:value="TextValue"
        placeholder="请输入审批意见"
        :rows="4"
      />
    </a-modal>
    <!-- 分时段优惠 -->
    <a-modal
      v-model:open="isDiscountOpen"
      width="1000px"
      title="分时段优惠"
      footer=""
    >
      <DiscountOpenDetail :data="discountData"></DiscountOpenDetail>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { reactive, toRaw, ref, computed, h } from 'vue';
import {
  getJFBZApprovaldList,
  JFBZApprovaldOperation,
  selectCommonId,
  selectCommon,
} from '#/api/core/planAudit';
import DiscountOpenDetail from './client_component/DiscountOpenDetail.vue';
import { message } from 'ant-design-vue';

const formState = reactive({
  apply: [], // 申请时间
  approval: [], // 审批时间
  approver: '', // 审批人
  approvalStatus: '', // 审批状态
  jfbzName: '', // 计划名称
});
const treeDataId = ref(); // 审批人树
// 查询和重置
const formRef = ref();
const onSubmit = () => {
  GetData();
  console.log(toRaw(formState));
};
const resetForm = () => {
  formRef.value.resetFields();
};

// 弹窗
interface row {
  id: string;
  type: string;
  approvalOpinion: string;
  approvalType: string;
  regionID: string;
  jfbzName: string;
  year: string;
}
const isConsentOpen = ref(false); // 同意弹窗
const TextValue = ref(''); // 审批意见
const ApprovalType = ref(''); // 审批类型
const rowData = ref(<row>{}); // 当前行数据
const onEdit = (data: any, type: string) => {
  console.log(data, type);
  if (type) {
    console.log('同意', type);
    rowData.value = data;
    isConsentOpen.value = true;
    TextValue.value = '';
    ApprovalType.value = type;
  } else {
    console.log('拒绝', type);
    rowData.value = data;
    isConsentOpen.value = true;
    TextValue.value = '';
    ApprovalType.value = type;
  }
};

const ConsentOk = async (e: MouseEvent) => {
  const res = await JFBZApprovaldOperation({
    id: rowData.value.id, //审批表id
    type: ApprovalType.value, //0同意 1 不同意
    approvalOpinion: TextValue.value, //审批意见
    approvalType: rowData.value.approvalType, //申请类型
    regionID: rowData.value.regionID, //regionID
    jfbzName: rowData.value.jfbzName, //标准名称
    year: rowData.value.year, //收费期
  });
  console.log(res);
  if (res.data.code === 200) {
    message.success(res.data.message || '操作成功');
  } else {
    message.error(res.data.msg || '操作失败');
  }
  GetData();
  isConsentOpen.value = false;
};

// 下载
// const downloadClick = async (data: any) => {
// };
// 优惠
const isDiscountOpen = ref(false); // 优惠弹窗
const discountData = ref();
const discountClick = async (data: any) => {
  console.log(data);
  isDiscountOpen.value = true;
  discountData.value = data;
};

const dataSource = ref();
const columns = [
  {
    title: '子公司',
    dataIndex: 'comName',
    key: 'comName',
    align: 'center',
    width: 180,
    ellipsis: true,
  },
  {
    title: '标准名称',
    dataIndex: 'jfbzName',
    key: 'jfbzName',
    align: 'center',
    width: 250,
    ellipsis: true,
  },
  {
    title: '开始使用日期',
    dataIndex: 'beginUseDate',
    key: 'beginUseDate',
    align: 'center',
    width: 120,
    ellipsis: true,
  },
  {
    title: '结束使用日期',
    dataIndex: 'endUseDate',
    key: 'endUseDate',
    align: 'center',
    width: 120,
    ellipsis: true,
  },
  // {
  //   title: '优惠类型',
  //   dataIndex: 'discountType',
  //   key: 'discountType',
  //   align: 'center',
  //   width: 120,
  //   ellipsis: true,
  // },
  {
    title: '供暖开始日期',
    dataIndex: 'heatingStartDate',
    key: 'heatingStartDate',
    align: 'center',
    width: 120,
    ellipsis: true,
  },
  {
    title: '供暖结束日期',
    dataIndex: 'heatingEndDate',
    key: 'heatingEndDate',
    align: 'center',
    width: 120,
    ellipsis: true,
  },
  {
    title: '供热天数',
    dataIndex: 'heatingDays',
    key: 'heatingDays',
    align: 'center',
    width: 100,
    ellipsis: true,
  },
  {
    title: '停供申请开始日期',
    dataIndex: 'suspensionStartDate',
    key: 'suspensionStartDate',
    align: 'center',
    width: 150,
    ellipsis: true,
  },
  {
    title: '停供申请结束日期',
    dataIndex: 'suspensionEndDate',
    key: 'suspensionEndDates',
    align: 'center',
    width: 150,
    ellipsis: true,
  },
  {
    title: '停供系数',
    dataIndex: 'suspensionRate',
    key: 'suspensionRate',
    align: 'center',
    width: 100,
    ellipsis: true,
  },
  {
    title: '居民面积单价',
    dataIndex: 'jmAreaPrice',
    key: 'jmAreaPrices',
    align: 'center',
    width: 120,
    ellipsis: true,
  },
  {
    title: '非居民面积单价',
    dataIndex: 'fjmAreaPrice',
    key: 'fjmAreaPrice',
    align: 'center',
    width: 130,
    ellipsis: true,
  },
  {
    title: '办公面积单价',
    dataIndex: 'bgAreaPrice',
    key: 'bgAreaPrice',
    align: 'center',
    width: 120,
    ellipsis: true,
  },
  {
    title: '经营面积单价',
    dataIndex: 'jyAreaPrice',
    key: 'jyAreaPrice',
    align: 'center',
    width: 120,
    ellipsis: true,
  },
  {
    title: '开始制冷时间',
    dataIndex: 'coolinStartDate',
    key: 'coolinStartDate',
    align: 'center',
    width: 120,
    ellipsis: true,
  },
  {
    title: '结束制冷时间',
    dataIndex: 'coolingEndDate',
    key: 'coolinEndDate',
    align: 'center',
    width: 120,
    ellipsis: true,
  },
  {
    title: '制冷天数',
    dataIndex: 'coolingDays',
    key: 'coolinDays',
    align: 'center',
    width: 100,
    ellipsis: true,
  },
  {
    title: '制冷居民单价',
    dataIndex: 'jmCoolingPrice',
    key: 'jmCoolingPrice',
    align: 'center',
    width: 130,
    ellipsis: true,
  },
  {
    title: '制冷非居民单价',
    dataIndex: 'fjmCoolingPrice',
    key: 'fjmCoolingPrice',
    align: 'center',
    width: 130,
    ellipsis: true,
  },
  {
    title: '制冷办公单价',
    dataIndex: 'bgCoolingPrice',
    key: 'bgCoolingPrice',
    align: 'center',
    width: 120,
    ellipsis: true,
  },
  {
    title: '制冷经营单价',
    dataIndex: 'jyCoolingPrice',
    key: 'jyCoolingPrice',
    align: 'center',
    width: 120,
    ellipsis: true,
  },
  {
    title: '滞纳金计算方式',
    dataIndex: 'lateFeeMethod',
    key: 'lateFeeMethod',
    align: 'center',
    width: 140,
    ellipsis: true,
  },
  {
    title: '滞纳金收取范围',
    dataIndex: 'lateFeeRange',
    key: 'lateFeeRange',
    align: 'center',
    width: 140,
    ellipsis: true,
  },
  {
    title: '滞纳金额',
    dataIndex: 'lateFeeAmount',
    key: 'lateFeeAmount',
    align: 'center',
    width: 100,
    ellipsis: true,
  },
  {
    title: '滞纳金比例',
    dataIndex: 'lateFeeRate',
    key: 'lateFeeRate',
    align: 'center',
    width: 110,
    ellipsis: true,
  },
  {
    title: '滞纳金开始日期',
    dataIndex: 'lateFeeStartDate',
    key: 'lateFeeStartDate',
    align: 'center',
    width: 140,
    ellipsis: true,
  },
  {
    title: '滞纳金结束日期',
    dataIndex: 'lateFeeEndDate',
    key: 'lateFeeEndDate',
    align: 'center',
    width: 140,
    ellipsis: true,
  },
  {
    title: '优惠类型',
    dataIndex: 'discountType',
    key: 'discountType',
    align: 'center',
    width: 100,
  },
  {
    title: '优惠比例固定优惠',
    dataIndex: 'discountRate',
    key: 'discountRate',
    align: 'center',
    width: 150,
    ellipsis: true,
  },
  {
    title: '优惠金额固定优惠',
    dataIndex: 'discountAmount',
    key: 'discountAmount',
    align: 'center',
    width: 150,
    ellipsis: true,
  },
  {
    title: '精确单位',
    dataIndex: 'precisionUnit',
    key: 'precisionUnit',
    align: 'center',
    width: 100,
    ellipsis: true,
  },
  {
    title: '最大抹零金额',
    dataIndex: 'maxTrimZeroMoney',
    key: 'maxTrimZeroMoney',
    align: 'center',
    width: 120,
    ellipsis: true,
  },
  {
    title: '舍入计算规则',
    dataIndex: 'roundingCalculationRule',
    key: 'roundingCalculationRule',
    align: 'center',
    width: 120,
    ellipsis: true,
  },
  {
    title: '是否允许挂账',
    dataIndex: 'onAccount',
    key: 'onAccount',
    align: 'center',
    width: 120,
    ellipsis: true,
  },
  {
    title: '审批状态',
    dataIndex: 'approvalStatus',
    key: 'approvalStatus',
    align: 'center',
    width: 120,
    ellipsis: true,
  },
  // {
  //   title: '审批人',
  //   dataIndex: 'approverName',
  //   key: 'approverName',
  //   align: 'center',
  //   width: 120,
  //   ellipsis: true,
  // },
  {
    title: '审批时间',
    dataIndex: 'approvalTime',
    key: 'approvalTime',
    align: 'center',
    width: 180,
    ellipsis: true,
  },
  {
    title: '审批意见',
    dataIndex: 'approvalOpinion',
    key: 'approvalOpinion',
    align: 'center',
    width: 180,
    ellipsis: true,
  },
  {
    title: '操作',
    dataIndex: 'active',
    key: 'active',
    align: 'center',
    fixed: 'right',
    width: 180,
  },
];
const current = ref(1); // 当前页码
const total = ref(0); // 总条数
const pageSize = ref(10); // 每页条数
// 分页
const pagination = computed(() => ({
  total: total.value,
  current: current.value,
  pageSize: pageSize.value,
}));
const handleTableChange = (pag: { current: number; pageSize: number }) => {
  console.log('分页参数', pag);
  current.value = pag.current;
  pageSize.value = pag.pageSize;
  GetData(); // 获取表格数据
};

// 获取表格数据
const GetData = async () => {
  console.log(formState);
  let res = await getJFBZApprovaldList({
    approvaldCheckData: {
      applicationTimeBegin:
        formState.apply && formState.apply[0] ? formState.apply[0] : '',
      applicationTimeEnd:
        formState.apply && formState.apply[1] ? formState.apply[1] : '',
      approvalTimeBegin:
        formState.approval && formState.approval[0]
          ? formState.approval[0]
          : '',
      approvalTimeEnd:
        formState.approval && formState.approval[1]
          ? formState.approval[1]
          : '',
      approvalStatus: formState.approvalStatus,
      approverId: formState.approver,
      jfbzName: formState.jfbzName,
    },
    limit: pageSize.value,
    page: current.value,
  });

  console.log(res);
  dataSource.value = res.data;
  total.value = res.total;
};
GetData();
// 修改初始化方法获取审批人下拉数据
const getSelectData = async () => {
  let res = await selectCommonId();
  treeDataId.value = res.map((item: any) => ({
    label: item.name,
    value: item.id || item.userId,
  }));
  console.log(treeDataId.value, '初始化');
};
// 修改onChange方法
const onChange = async (value: any, node: any) => {
  console.log(value, node, 'onChange');
  const res = await selectCommon(value);
  treeDataId.value = updateChildren(treeDataId.value, value, res); // 递归更新子节点
};
const updateChildren = (
  nodes: any[],
  targetValue: string,
  newChildren: any[],
) => {
  return nodes.map((node) => {
    // 当前节点匹配时添加子节点
    if (node.value === targetValue) {
      return {
        ...node,
        children: newChildren.map((child) => ({
          label: child.name,
          value: child.id || child.userId,
          children: [], // 初始化空children用于继续展开
        })),
      };
    }

    // 递归处理子节点
    if (node.children && node.children.length > 0) {
      return {
        ...node,
        children: updateChildren(node.children, targetValue, newChildren),
      };
    }

    return node;
  });
};
getSelectData();
</script>

<style scoped></style>
